<?php
// 包含数据库连接文件
require_once 'conn.php';
session_start();

// 获取当前登录用户ID
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
if ($user_id == 0) {
  echo "<script>alert('用户未登录'); window.location.href = 'login.php';</script>";
  exit;
}

// 获取支付方式
$payment_method = isset($_POST['payment_method']) ? $_POST['payment_method'] : '';

// 获取购物车中的所有商品
$sql = "SELECT * FROM cart WHERE user_id = $user_id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // 遍历购物车商品
  while ($cart_item = $result->fetch_assoc()) {
    $product_id = $cart_item['product_id'];
    $quantity = $cart_item['quantity'];
    $total = $cart_item['total']; // 购物车中的总价

    // 插入订单数据
    $order_sql = "INSERT INTO orders (product_id, user_id, quantity, total, date, method) 
                  VALUES ($product_id, $user_id, '$quantity', '$total', NOW(), '$payment_method')";
    
    if ($conn->query($order_sql) === TRUE) {
      // 更新库存（假设库存字段存在，并且是数字类型）
      $update_stock_sql = "UPDATE products SET stock = stock - $quantity WHERE id = $product_id";
      $conn->query($update_stock_sql);
    } else {
      echo "<script>alert('结算失败，请重试'); window.history.back();</script>";
      exit;
    }
  }

  // 删除购物车中的商品（结算完成后）
  $delete_cart_sql = "DELETE FROM cart WHERE user_id = $user_id";
  if ($conn->query($delete_cart_sql) === TRUE) {
    echo "<script>alert('结算成功，感谢您的购买'); window.location.href = 'my_orders.php';</script>";
  } else {
    echo "<script>alert('结算失败，请重试'); window.history.back();</script>";
  }
} else {
  echo "<script>alert('购物车为空'); window.history.back();</script>";
}

$conn->close();
?>
